import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import { Form, Input, Button, notification, Select } from 'antd';
import { FormComponentProps } from "antd/lib/form/Form";

interface IProps extends FormComponentProps {
  dispatch?: Function,
  data?: {
    id: number | string,
    name: string,
    remark: string
  },
  history?: any,
  keys?: Array<string>
}

interface IState {
  confirmDirty: boolean,
  autoCompleteResult: Array<any>,
  isNew: boolean
}

@connect()
class FormItem extends Component<IProps, IState> {
  readonly state: IState = {
    confirmDirty: false,
    autoCompleteResult: [],
    isNew: true
  };

  componentDidMount() {
    const { data, form } = this.props;
    if (data) {
      const { name, remark } = data;
      form.setFieldsValue({
        name,
        remark
      })
    }
  }

  handleSubmit = (e) => {
    e.preventDefault();

    const { form, data, dispatch } = this.props;

    form.validateFields((err, values) => {
      if (!err) {
        data && data.id ? dispatch({
          type: 'group/update',
          payload: {
            id: data.id,
            ...values
          }
        }) : dispatch({
          type: 'group/create',
          payload: values
        })
      } else {
        notification['error']({
          message: `${data.id ? '修改' : '创建'}失败`,
          description: '字段验证不通过',
        });
      }
    })
  }

  render() {
    const { form, data } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 8 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 12,
          offset: 0,
        },
        sm: {
          span: 8,
          offset: 4,
        },
      },
    };
    return (
      <Form onSubmit={this.handleSubmit}>
        <Form.Item
          {...formItemLayout}
          label="部门名称"
        >
          {getFieldDecorator('name', {
            rules: [{
              required: true, message: '请输入部门',
            }],
          })(
            <Input placeholder='请输入部门名称' />
          )}
        </Form.Item>
        <Form.Item
          {...formItemLayout}
          label='备注'
        >
          {getFieldDecorator('remark', {
            rules: [{ required: false, message: '请输入备注', whitespace: true }],
          })(
            <Input placeholder='请输入备注' />
          )}
        </Form.Item>
        <Form.Item {...tailFormItemLayout}>
          <Button type="primary" htmlType="submit">{ !!data ? '修改' : '新建' }</Button>
          <Link to='/data/group'>
            <Button style={{ marginLeft: '5%' }}>返回列表</Button>
          </Link>
        </Form.Item>
      </Form>
    );
  }
}

const FormList = Form.create()(FormItem);
export default FormList;